const router = require('koa-router')()
const jwt = require("jsonwebtoken");
const myKey = "214ii";
const svgCaptcha = require('svg-captcha');

router.get('/', async (ctx, next) => {
  await ctx.render('index', {
    title: 'Hello Koa 2!'
  })
})

// 验证码
router.get('/captcha',(ctx,next)=>{
  const captcha = svgCaptcha.create({
    size: 4,
    fontSize: 36,
    ignoreChars: '0oO1iIl', 
    noise: 3, 
    color: false,
    background: '#cc9966' ,
    height:38,
    width:44
  })
  const img = captcha.data
  const text = captcha.text
  ctx.body={
    img:img,
    text:text
  }
})

// 账号验证
router.post('/check',async(ctx,next)=>{
  let number=ctx.request.body.number;
  let pass=ctx.request.body.pass;
  let check=ctx.request.body.check;
  console.log(ctx.request.body);
  let userJson=ctx.request.body.userJson;
  let code=ctx.request.body.code;
  // ctx.body.code  300 验证码错误
  //  0 用户名和密码错误
  // 100 用户名错误
  // 400 密码错误
  // 200 验证成功
  if(check != code){
    ctx.body={"code":300,"msg":"warning"};
  }else{
    if(number != userJson.username &&  pass != userJson.pwd){
      ctx.body={"code":0,"msg":"warning"};
    }
    else if(number != userJson.username &&  pass == userJson.pwd){
      ctx.body={"code":100,"msg":"warning"};
    }
    else if(number == userJson.username &&  pass != userJson.pwd){
      ctx.body={"code":400,"msg":"warning"};
    }else{
      ctx.body={"code":200,"msg":"success"};
    }

  }
})

let fileList=new Array() ;
router.post('/upload',async(ctx,next)=>{
  let filetype=ctx.request.body.fileType;
  if(filetype=="image/jpeg" ||filetype== "image/png"){
    let token=jwt.sign({filetype:"image/jpeg"},myKey);
    ctx.body={"code":200,"msg":"success",token:token};
    fileList.push(ctx.request.body);
  }else{
    ctx.body={"code":500,"msg":"图片格式错误",fileList:fileList};
  }
  // console.log(fileList);
})

router.get('/getlist', async (ctx, next) => {
  ctx.body = fileList;
})

router.post('/del',async(ctx,next)=>{
  let id=ctx.request.body.id;
  let index='';
  for(let i=0;i<fileList.length;i++){
    if(fileList[i]["fileId"]==id){
      index=i;
    }
  }
  fileList.splice(index,1);
  ctx.body="success";
})
module.exports = router
